import Vue from 'vue'
import VueRouter from 'vue-router'
// 1导入路由
import login from "@/views/user/login.vue"
import home from "@/views/home/home.vue"
import qa from "@/views/qa/qa.vue"
import movie from "@/views/movie/movie.vue"
import user from "@/views/user/user.vue"
import layout from "@/views/user/layout.vue"
import edit from "@/views/user/edit.vue"
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/user/student.vue'



Vue.use(VueRouter)

// 路由配置
// 一级路由
const routes = [{
    path: '/login',
    name: 'long',
    component: login
  },
  ,
  {
    path:'/student',
    name:'student',
    component: student
  },
  {
    path:'/article',
    name:'myarticle',
    component: article
  },
  {
    path:'/edit',
    name:'edit',
    component: edit
  },
  {
    name:"searchResult",
    path:'/searchResult',
    component:searchResult,
  },{
    name:"search",
    path:'/search',
    component:search,
  },
  {
    path: '/',
    name: 'layout',
    component: layout,
    // 二级路由
    children: [{
        path: '/home',
        name: 'home',
        component: home
      }, {
        path: '/qa',
        name: 'qa',
        component: qa
      }, {
        path: '/movie',
        name: 'movie',
        component: movie
      }, {
        path: '/user',
        name: 'user',
        component: user,
        meta:{
          isLogin:true
        }
      },
      {
        path: '/',
        redirect: '/home'
      },
    ]
  },

]


const router = new VueRouter({
  routes
})
import { getToken } from '@/utils/token.js'
import { Toast } from 'vant'


/* 注册路由前置导航守卫 */
router.beforeEach((to, from, next) => {
  // ...
  //to: 要跳转的路由 （要到那里去）
  // console.log(to)
  //from : 从哪个路由跳转（从哪里来）
  // console.log(from)
  /*next : ***必须要调用的，否则路由无法跳转*** 
  next() :没有传参。 通过检查 。 允许跳转to页面
  next('/path') :传参数. 没有通过检查 。跳转到指定页面
  */
  /* 并不是所有的页面都需要做登录判断，把需要登录判断的页面添加meta */
  if( to.meta.isLogin ){
    //需要做登录判断
    if( getToken() ){
      //有登录,不拦截，允许正常跳转
      next()
    }else{
      //没登录，进行拦截。 跳转登录页
      //弹窗提示
      Toast.fail('请先登录')
      //跳转登录页
      next({path:'/login'})
    }
  }else{
    //不需要做登录判断，无条件跳转
    next()
  }
 
})

export default router
